<template>
  <div class="branch-profile-view">
    <!-- 左侧：支行列表 -->
    <div class="branch-list-panel">
      <div class="panel-header">
        <div class="header-title">机构综合评分</div>
        <div class="header-subtitle" v-if="!isLoadingScores">共 {{ branches.length }} 个支行</div>
        <div class="header-subtitle" v-else>加载中...</div>
      </div>
      
      <div class="branch-list-container" v-if="!isLoadingScores">
        <div 
          v-for="(branch, index) in branchesWithScores" 
          :key="branch.orgNo"
          class="branch-list-item"
          :class="{ active: selectedBranch === branch.orgNo }"
          @click="selectBranch(branch.orgNo)"
        >
          <div class="branch-rank">{{ index + 1 }}</div>
          <div class="branch-info">
            <div class="branch-name">{{ branch.name }}</div>
            <div class="branch-org-no">{{ branch.orgNo }}</div>
          </div>
          <div class="branch-score">
            <div class="score-value" :class="getScoreClass(branch.score)">
              {{ typeof branch.score === 'number' ? branch.score.toFixed(2) : '0.00' }}
            </div>
            <div class="score-label">分</div>
          </div>
        </div>
      </div>
      
      <!-- 左侧加载状态 -->
      <div v-else class="list-loading">
        <div class="loading-spinner-small"></div>
        <div class="loading-text-small">正在加载评分数据...</div>
      </div>
    </div>

    <!-- 右侧：支行详情 -->
    <div class="branch-detail-panel">
      <!-- 未选择支行时的提示 -->
      <div v-if="!selectedBranch" class="no-selection">
        <div class="no-selection-icon">🏦</div>
        <div class="no-selection-text">请从左侧列表选择一个支行查看详情</div>
      </div>

      <!-- 加载状态 -->
      <div v-else-if="isLoading" class="loading-container">
        <div class="loading-spinner"></div>
        <div class="loading-text">正在加载支行数据...</div>
      </div>

      <!-- 支行详情内容 -->
      <div v-else class="branch-content">
        <!-- 支行标题区 -->
        <div class="branch-header">
          <div class="branch-title">
            <h2>{{ getBranchName(selectedBranch) }}</h2>
            <span class="branch-code">机构号：{{ selectedBranch }}</span>
          </div>
          <div class="branch-score-display">
            <div class="score-circle" :class="getScoreClass(getCurrentBranchScore())">
              <div class="score-number">{{ getCurrentBranchScore().toFixed(2) }}</div>
              <div class="score-text">综合评分</div>
            </div>
          </div>
        </div>

        <!-- 第一部分：基础情况 -->
        <div class="section section-basic">
          <div class="box">
            <div class="tit">
              <span>基础情况</span>
            </div>
            <div class="basic-info-grid">
              <!-- 员工人数 -->
              <div class="basic-info-card">
                <div class="info-icon">👥</div>
                <div class="info-content">
                  <div class="info-label">员工人数</div>
                  <div class="info-value">
                    <span class="value-number">{{ basicInfo.staffCount }}</span>
                    <span class="value-unit">人</span>
                  </div>
                  <div class="info-change" :class="basicInfo.staffChange >= 0 ? 'positive' : 'negative'">
                    较上月 {{ basicInfo.staffChange >= 0 ? '+' : '' }}{{ basicInfo.staffChange }}人
                  </div>
                </div>
              </div>

              <!-- 贷款规模 -->
              <div class="basic-info-card">
                <div class="info-icon">💰</div>
                <div class="info-content">
                  <div class="info-label">贷款余额</div>
                  <div class="info-value">
                    <span class="value-number">{{ basicInfo.loanBalance }}</span>
                    <span class="value-unit">亿元</span>
                  </div>
                  <div class="info-change" :class="basicInfo.loanGrowth >= 0 ? 'positive' : 'negative'">
                    较年初 {{ basicInfo.loanGrowth >= 0 ? '+' : '' }}{{ basicInfo.loanGrowth }}%
                  </div>
                </div>
              </div>

              <!-- 存款规模 -->
              <div class="basic-info-card">
                <div class="info-icon">💵</div>
                <div class="info-content">
                  <div class="info-label">存款余额</div>
                  <div class="info-value">
                    <span class="value-number">{{ basicInfo.depositBalance }}</span>
                    <span class="value-unit">亿元</span>
                  </div>
                  <div class="info-change" :class="basicInfo.depositGrowth >= 0 ? 'positive' : 'negative'">
                    较年初 {{ basicInfo.depositGrowth >= 0 ? '+' : '' }}{{ basicInfo.depositGrowth }}%
                  </div>
                </div>
              </div>

              <!-- 不良贷款率 -->
              <div class="basic-info-card">
                <div class="info-icon">⚠️</div>
                <div class="info-content">
                  <div class="info-label">不良贷款率</div>
                  <div class="info-value">
                    <span class="value-number">{{ basicInfo.nplRatio }}</span>
                    <span class="value-unit">%</span>
                  </div>
                  <div class="info-change" :class="basicInfo.nplChange <= 0 ? 'positive' : 'negative'">
                    较年初 {{ basicInfo.nplChange >= 0 ? '+' : '' }}{{ basicInfo.nplChange }}%
                  </div>
                </div>
              </div>

              <!-- 中间业务收入占比 -->
              <div class="basic-info-card">
                <div class="info-icon">💼</div>
                <div class="info-content">
                  <div class="info-label">中间业务收入占比</div>
                  <div class="info-value">
                    <span class="value-number">{{ basicInfo.middleIncomeRatio }}</span>
                    <span class="value-unit">%</span>
                  </div>
                  <div class="info-change" :class="basicInfo.middleIncomeChange >= 0 ? 'positive' : 'negative'">
                    较年初 {{ basicInfo.middleIncomeChange >= 0 ? '+' : '' }}{{ basicInfo.middleIncomeChange }}%
                  </div>
                </div>
              </div>

              <!-- 合规得分 -->
              <div class="basic-info-card">
                <div class="info-icon">✅</div>
                <div class="info-content">
                  <div class="info-label">合规得分</div>
                  <div class="info-value">
                    <span class="value-number">{{ basicInfo.complianceScore }}</span>
                    <span class="value-unit">分</span>
                  </div>
                  <div class="info-change" :class="getComplianceLevel(basicInfo.complianceScore)">
                    {{ getComplianceLevelText(basicInfo.complianceScore) }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 第二部分：异常指标分析 -->
        <div class="section section-abnormal-indicators" v-if="selectedBranch">
          <div class="box">
            <div class="tit">
              <span>异常指标分析</span>
              <span class="tit-subtitle" v-if="abnormalIndicators.length > 0">
                共 {{ abnormalIndicators.length }} 项 (Z-score 绝对值 > 1)
              </span>
            </div>
            
            <div class="abnormal-content">
              <div v-if="abnormalIndicators.length === 0" class="no-abnormal">
                <div class="no-abnormal-icon">✅</div>
                <div class="no-abnormal-text">该支行所有指标表现正常，无显著偏离</div>
              </div>
              
              <div v-else class="abnormal-grid">
                <!-- 优秀指标 -->
                <div v-if="excellentIndicators.length > 0" class="indicator-group">
                  <div class="group-header excellent-header">
                    <span class="group-icon">✨</span>
                    <span class="group-title">表现优秀</span>
                    <span class="group-count">{{ excellentIndicators.length }} 项</span>
                  </div>
                  <div class="indicator-cards">
                    <div 
                      v-for="item in excellentIndicators" 
                      :key="item.key"
                      class="indicator-card excellent"
                    >
                      <div class="card-header">
                        <span class="indicator-name">{{ item.name }}</span>
                        <span class="zscore-badge zscore-high">
                          Z: {{ item.zScore.toFixed(2) }}
                        </span>
                      </div>
                      <div class="card-body">
                        <div class="metric-row">
                          <span class="metric-label">实际值</span>
                          <span class="metric-value">{{ formatIndicatorValue(item.value) }}</span>
                        </div>
                        <div class="metric-row">
                          <span class="metric-label">得分</span>
                          <span class="metric-value score-value">{{ item.score.toFixed(2) }} 分</span>
                        </div>
                      </div>
                      <div class="card-footer">
                        <span class="indicator-type">{{ item.isPositive ? '正向指标' : '负向指标' }}</span>
                      </div>
                    </div>
                  </div>
                </div>
                
                <!-- 风险指标 -->
                <div v-if="riskIndicators.length > 0" class="indicator-group">
                  <div class="group-header risk-header">
                    <span class="group-icon">⚠️</span>
                    <span class="group-title">需要关注</span>
                    <span class="group-count">{{ riskIndicators.length }} 项</span>
                  </div>
                  <div class="indicator-cards">
                    <div 
                      v-for="item in riskIndicators" 
                      :key="item.key"
                      class="indicator-card risk"
                    >
                      <div class="card-header">
                        <span class="indicator-name">{{ item.name }}</span>
                        <span class="zscore-badge zscore-low">
                          Z: {{ item.zScore.toFixed(2) }}
                        </span>
                      </div>
                      <div class="card-body">
                        <div class="metric-row">
                          <span class="metric-label">实际值</span>
                          <span class="metric-value">{{ formatIndicatorValue(item.value) }}</span>
                        </div>
                        <div class="metric-row">
                          <span class="metric-label">得分</span>
                          <span class="metric-value score-value">{{ item.score.toFixed(2) }} 分</span>
                        </div>
                      </div>
                      <div class="card-footer">
                        <span class="indicator-type">{{ item.isPositive ? '正向指标' : '负向指标' }}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 第三部分：前十大贷款户 -->
        <div class="section section-top-loans">
          <div class="box">
            <div class="tit">
              <span>前十大贷款户</span>
            </div>
            
            <div class="top-loans-content">
              <div v-if="isLoadingTopLoans" class="loading-container-small">
                <div class="loading-spinner-small"></div>
                <div class="loading-text-small">加载数据中...</div>
              </div>
              <div v-else-if="currentTopLoans.length === 0" class="empty-container-small">
                <div class="empty-message">暂无数据</div>
              </div>
              <div v-else class="loans-list-table">
                <table>
                  <thead>
                    <tr>
                      <th class="text-center">排名</th>
                      <th>客户名称</th>
                      <th class="text-right">贷款余额(万元)</th>
                      <th class="text-center">借据数量</th>
                      <th class="text-center">操作</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr v-for="(customer, index) in currentTopLoans" :key="index" @click="showCustomerDetail(customer)">
                      <td class="rank-cell">
                        <span class="rank-badge" :class="getRankClass(index)">{{ index + 1 }}</span>
                      </td>
                      <td class="customer-name">{{ customer.name }}</td>
                      <td class="amount-wan">{{ (customer.value / 10000).toFixed(2) }}</td>
                      <td class="loan-count">{{ customer.loanCount }} 笔</td>
                      <td class="action-cell">
                        <button class="detail-btn" @click.stop="showCustomerDetail(customer)">查看详情</button>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>

        <!-- 第三部分：前十大不良贷款户 -->
        <div class="section section-top-bad-loans">
          <div class="box">
            <div class="tit">
              <span>前十大不良贷款户</span>
            </div>
            
            <div class="top-bad-loans-content">
              <div v-if="isLoadingTopLoans" class="loading-container-small">
                <div class="loading-spinner-small"></div>
                <div class="loading-text-small">加载数据中...</div>
              </div>
              <div v-else-if="currentTopBadLoans.length === 0" class="empty-container-small">
                <div class="empty-message">暂无数据</div>
              </div>
              <div v-else class="loans-list-table bad-loans-table">
                <table>
                  <thead>
                    <tr>
                      <th class="text-center">排名</th>
                      <th>客户名称</th>
                      <th class="text-right">不良贷款余额(万元)</th>
                      <th class="text-center">借据数量</th>
                      <th class="text-center">操作</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr v-for="(customer, index) in currentTopBadLoans" :key="index" @click="showCustomerDetail(customer)">
                      <td class="rank-cell">
                        <span class="rank-badge bad-rank" :class="getRankClass(index)">{{ index + 1 }}</span>
                      </td>
                      <td class="customer-name">{{ customer.name }}</td>
                      <td class="amount-wan bad-amount">{{ (customer.value / 10000).toFixed(2) }}</td>
                      <td class="loan-count">{{ customer.loanCount }} 笔</td>
                      <td class="action-cell">
                        <button class="detail-btn" @click.stop="showCustomerDetail(customer)">查看详情</button>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 客户详情弹窗 -->
    <div v-if="showDetailDialog" class="detail-dialog-overlay" @click="showDetailDialog = false">
      <div class="detail-dialog" @click.stop>
        <div class="dialog-header">
          <h3>{{ selectedCustomer?.name }} - 借据详情</h3>
          <button class="close-btn" @click="showDetailDialog = false">✕</button>
        </div>
        <div class="dialog-body">
          <div class="customer-summary">
            <div class="summary-item">
              <span class="label">贷款总额:</span>
              <span class="value">{{ (selectedCustomer?.value / 10000 / 10000).toFixed(2) }} 亿元</span>
            </div>
            <div class="summary-item">
              <span class="label">借据数量:</span>
              <span class="value">{{ selectedCustomer?.loanCount }} 笔</span>
            </div>
          </div>
          
          <div class="loans-table">
            <table>
              <thead>
                <tr>
                  <th>序号</th>
                  <th>借据号/卡号</th>
                  <th>合同编号</th>
                  <th>产品类型</th>
                  <th>五级分类</th>
                  <th>贷款金额(万元)</th>
                  <th>贷款余额(万元)</th>
                  <th>贷款余额(元)</th>
                  <th>放款日期</th>
                  <th>到期日期</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(loan, index) in selectedCustomer?.loans" :key="index">
                  <td>{{ index + 1 }}</td>
                  <td class="text-highlight">{{ loan.loanId || loan.cardNo || '-' }}</td>
                  <td>{{ loan.contractNo || '-' }}</td>
                  <td>{{ loan.productName || '-' }}</td>
                  <td>
                    <span class="risk-badge" :class="getRiskClass(loan.riskLevel)">
                      {{ getRiskLabel(loan.riskLevel) }}
                    </span>
                  </td>
                  <td class="text-right">{{ (loan.loanAmount / 10000).toFixed(2) }}</td>
                  <td class="text-right text-amount">{{ (loan.balance / 10000).toFixed(2) }}</td>
                  <td class="text-right">{{ loan.balance.toLocaleString('zh-CN', { maximumFractionDigits: 2 }) }}</td>
                  <td>{{ loan.loanDate || '-' }}</td>
                  <td>{{ loan.dueDate || '-' }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useBranchScoreStore } from '../stores/branchScoreStore.js'
import { loadBranchScores } from '../utils/scoreDB.js'
import { useBranchTopLoans } from '../composables/useBranchTopLoans.js'

/**
 * 机构号与名称的映射关系（从 useComprehensiveScore.js 引入）
 */
const ORG_NAME_MAP = {
  '00000': '东莞农村商业银行',
  '01000': '中堂支行',
  '02000': '望牛墩支行',
  '03000': '道滘支行',
  '04000': '洪梅支行',
  '05000': '麻涌支行',
  '06000': '万江支行',
  '07000': '虎门支行',
  '08000': '长安支行',
  '09000': '厚街支行',
  '10000': '沙田支行',
  '11000': '南城支行',
  '12000': '东城支行',
  '13000': '寮步支行',
  '14000': '大岭山支行',
  '15000': '大朗支行',
  '16000': '黄江支行',
  '17000': '樟木头支行',
  '18000': '清溪支行',
  '19000': '塘厦支行',
  '20000': '凤岗支行',
  '21000': '谢岗支行',
  '22000': '常平支行',
  '23000': '桥头支行',
  '24000': '横沥支行',
  '25000': '东坑支行',
  '26000': '企石支行',
  '27000': '石排支行',
  '28000': '茶山支行',
  '29000': '石碣支行',
  '30000': '高埗支行',
  '31000': '东联支行',
  '32000': '石龙支行',
  '33000': '松山湖科技支行',
  '37000': '总行(并表)',
  '38000': '中心支行',
  '39000': '私人银行部',
  '50000': '惠州支行',
  '51000': '清新支行',
  '52000': '南沙分行',
  '53000': '横琴分行',
  '55000': '滨海湾新区支行'
}

// 排除的非支行机构号
const EXCLUDED_ORG_NOS = ['00000', '37000', '39000']

// 使用评分存储（仅读取，不发起任何请求）
const branchScoreStore = useBranchScoreStore()

// 从 ORG_NAME_MAP 动态生成支行列表（排除总行等非支行机构）
const branches = computed(() => {
  return Object.entries(ORG_NAME_MAP)
    .filter(([orgNo]) => !EXCLUDED_ORG_NOS.includes(orgNo))
    .map(([orgNo, name]) => ({ orgNo, name }))
})

// 当前选中的支行
const selectedBranch = ref('')

// 加载状态
const isLoading = ref(false)

// 使用store中的评分数据（不需要本地存储）
const branchScores = computed(() => branchScoreStore.getScores())
const isLoadingScores = computed(() => branchScoreStore.isLoading.value)
const hasScoreData = computed(() => branchScoreStore.hasData.value)

// 前十大贷款户相关
const { fetchBranchTopLoans, fetchBranchTopBadLoans } = useBranchTopLoans()
const isLoadingTopLoans = ref(false)
const showDetailDialog = ref(false)
const selectedCustomer = ref(null)

// 异常指标分析相关
const abnormalIndicators = computed(() => {
  if (!selectedBranch.value) return []
  
  const rawData = branchScoreStore.getRawData()
  if (!rawData || !rawData.scoreResult) return []
  
  const branchData = rawData.scoreResult.branches[selectedBranch.value]
  if (!branchData || !branchData.scores) return []
  
  const abnormalList = []
  
  Object.entries(branchData.scores).forEach(([key, scoreInfo]) => {
    const zScore = Number(scoreInfo.zScore)
    const isPositive = scoreInfo.isPositive
    
    // 判断是否异常：Z-score 绝对值 > 1
    if (!isNaN(zScore) && Math.abs(zScore) > 1) {
      let type, zScoreClass
      
      if (isPositive) {
        // 正向指标：Z-score > 1 优秀，< -1 风险
        type = zScore > 1 ? 'excellent' : 'high-risk'
        zScoreClass = zScore > 1 ? 'zscore-high' : 'zscore-low'
      } else {
        // 负向指标：Z-score > 1 风险，< -1 优秀
        type = zScore > 1 ? 'high-risk' : 'excellent'
        zScoreClass = zScore > 1 ? 'zscore-high' : 'zscore-low'
      }
      
      abnormalList.push({
        key,
        name: scoreInfo.name,
        value: scoreInfo.originalValue,
        zScore: zScore,
        score: scoreInfo.score,
        type: type,
        zScoreClass: zScoreClass,
        isPositive: isPositive
      })
    }
  })
  
  // 按 Z-score 绝对值排序（从大到小）
  return abnormalList.sort((a, b) => Math.abs(b.zScore) - Math.abs(a.zScore))
})

// 优秀指标
const excellentIndicators = computed(() => {
  return abnormalIndicators.value.filter(item => item.type === 'excellent')
})

// 风险指标
const riskIndicators = computed(() => {
  return abnormalIndicators.value.filter(item => item.type === 'high-risk')
})

// 格式化指标值
const formatIndicatorValue = (value) => {
  if (typeof value === 'number') {
    return value.toLocaleString('zh-CN', { maximumFractionDigits: 2 })
  }
  return value || '-'
}

// 当前支行的前十大贷款户数据
const currentTopLoans = computed(() => {
  if (!selectedBranch.value) {
    console.log('[机构画像] 未选择支行，返回空数组')
    return []
  }
  const data = branchScoreStore.getTopLoans(selectedBranch.value)
  console.log(`[机构画像] 当前支行 ${selectedBranch.value} 前十大贷款户:`, data)
  return data
})

// 当前支行的前十大不良贷款户数据
const currentTopBadLoans = computed(() => {
  if (!selectedBranch.value) {
    console.log('[机构画像] 未选择支行，返回空数组')
    return []
  }
  const data = branchScoreStore.getTopBadLoans(selectedBranch.value)
  console.log(`[机构画像] 当前支行 ${selectedBranch.value} 前十大不良贷款户:`, data)
  return data
})

// 带评分的支行列表（按评分降序排列）
const branchesWithScores = computed(() => {
  return branches.value
    .map(branch => ({
      ...branch,
      score: branchScoreStore.getScore(branch.orgNo) || 0
    }))
    .sort((a, b) => b.score - a.score)
})

// 基础情况数据（从 store 读取）
const basicInfo = ref({
  staffCount: 0,
  staffChange: 0,
  loanBalance: 0,
  loanGrowth: 0,
  depositBalance: 0,
  depositGrowth: 0,
  nplRatio: 0,
  nplChange: 0,
  middleIncomeRatio: 0,
  middleIncomeChange: 0,
  complianceScore: 0
})

// 获取支行名称（使用 ORG_NAME_MAP）
const getBranchName = (orgNo) => {
  return ORG_NAME_MAP[orgNo] || orgNo
}

// 选择支行
const selectBranch = async (orgNo) => {
  if (selectedBranch.value === orgNo) return
  
  selectedBranch.value = orgNo
  isLoading.value = true
  
  console.log('[机构塑像] 选择支行:', orgNo, getBranchName(orgNo))
  
  // 模拟数据加载
  await new Promise(resolve => setTimeout(resolve, 300))
  
  // 加载支行数据
  await loadBranchData(orgNo)
  
  isLoading.value = false
}

// 加载支行数据（从 store 读取）
const loadBranchData = async (orgNo) => {
  console.log('[机构塑像] 加载支行数据:', orgNo)
  
  // 从 store 读取原始数据
  const rawData = branchScoreStore.getRawData()
  
  console.log('[机构塑像] Store 原始数据完整结构:', rawData)
  
  if (!rawData || !rawData.scoreData) {
    console.warn('[机构塑像] Store 中没有原始数据')
    return
  }
  
  console.log('[机构塑像] scoreData 的所有支行:', Object.keys(rawData.scoreData))
  
  const branchData = rawData.scoreData[orgNo]
  if (!branchData) {
    console.warn('[机构塑像] 找不到支行', orgNo, '的数据')
    console.log('[机构塑像] 可用的支行机构号:', Object.keys(rawData.scoreData).slice(0, 5))
    return
  }
  
  console.log('[机构塑像] 支行原始数据完整结构:', branchData)
  console.log('[机构塑像] 支行原始数据的所有字段:', Object.keys(branchData))
  
  // 辅助函数：从 API 返回的数据结构中提取值
  const extractValue = (dataObj, field = 'endResult') => {
    if (!dataObj || !dataObj.success) return null
    
    // 对于 single 类型，直接从 result 读取
    if (dataObj.type === 'single' && dataObj.result?.datas?.[0]) {
      return parseFloat(dataObj.result.datas[0][3]) // 第4列是值
    }
    
    // 对于 growth/increase/ratio 类型，从 endResult 读取
    if (dataObj[field]?.datas?.[0]) {
      return parseFloat(dataObj[field].datas[0][3])
    }
    
    return null
  }
  
  // 计算增长率
  const calculateGrowth = (dataObj) => {
    if (!dataObj || !dataObj.endResult || !dataObj.startResult) return 0
    const endVal = parseFloat(dataObj.endResult.datas[0][3])
    const startVal = parseFloat(dataObj.startResult.datas[0][3])
    if (startVal === 0) return 0
    return ((endVal - startVal) / startVal * 100).toFixed(1)
  }
  
  // 计算比率（分子/分母）
  const calculateRatio = (dataObj) => {
    if (!dataObj || !dataObj.numeratorResult || !dataObj.denominatorResult) return 0
    
    // 分子可能有多条数据（需要求和）
    let numerator = 0
    if (dataObj.numeratorResult.datas) {
      dataObj.numeratorResult.datas.forEach(row => {
        numerator += parseFloat(row[3])
      })
    }
    
    const denominator = parseFloat(dataObj.denominatorResult.datas[0][3])
    if (denominator === 0) return 0
    return ((numerator / denominator) * 100).toFixed(2)
  }
  
  // 从 store 中提取数据并格式化
  basicInfo.value = {
    // 员工人数（从 profitPerCapita 的分母中提取）
    staffCount: Math.round(extractValue(branchData.profitPerCapita, 'denominatorResult') || 0),
    staffChange: 0, // TODO: 需要历史数据来计算变化
    
    // 贷款余额（转换为亿元）
    loanBalance: extractValue(branchData.totalLoan, 'endResult') 
      ? (extractValue(branchData.totalLoan, 'endResult') / 100000000).toFixed(2)
      : '0.00',
    loanGrowth: calculateGrowth(branchData.totalLoan),
    
    // 存款余额（转换为亿元）
    depositBalance: extractValue(branchData.depositGrowth, 'endResult') 
      ? (extractValue(branchData.depositGrowth, 'endResult') / 100000000).toFixed(2)
      : '0.00',
    depositGrowth: calculateGrowth(branchData.depositGrowth),
    
    // 不良贷款率（已经是百分比）
    nplRatio: (extractValue(branchData.badLoanRate) || 0).toFixed(2),
    nplChange: 0, // TODO: 需要历史数据来计算变化
    
    // 中间业务收入占比（百分比）
    middleIncomeRatio: calculateRatio(branchData.intermediateIncomeRatio),
    middleIncomeChange: calculateGrowth(branchData.intermediateIncomeGrowth),
    
    // 合规得分（风险合规得分）
    complianceScore: (extractValue(branchData.riskComplianceScore) || 0).toFixed(1)
  }
  
  console.log('[机构塑像] 格式化后的基础信息:', basicInfo.value)
}

// 获取当前支行评分
const getCurrentBranchScore = () => {
  return branchScoreStore.getScore(selectedBranch.value)
}

// 根据评分获取样式类
const getScoreClass = (score) => {
  if (score >= 90) return 'score-excellent'
  if (score >= 80) return 'score-good'
  if (score >= 70) return 'score-normal'
  return 'score-poor'
}

// 获取合规得分等级样式
const getComplianceLevel = (score) => {
  if (score >= 90) return 'positive'
  if (score >= 80) return 'positive'
  if (score >= 70) return 'neutral'
  return 'negative'
}

// 获取合规得分等级文字
const getComplianceLevelText = (score) => {
  if (score >= 90) return '优秀'
  if (score >= 80) return '良好'
  if (score >= 70) return '合格'
  if (score >= 60) return '待改进'
  return '不合格'
}

// 组件挂载
onMounted(async () => {
  console.log('[机构塑像] 组件已挂载')
  console.log('[机构塑像] 从store读取评分数据:', branchScoreStore.branchScores.value)
  console.log('[机构塑像] 评分数据数量:', Object.keys(branchScores.value).length, '个支行')
  console.log('[机构塑像] hasScoreData:', hasScoreData.value)
  
  // 再次检查
  if (hasScoreData.value) {
    console.log('[机构塑像] 评分数据示例:', Object.entries(branchScores.value).slice(0, 3))
  } else {
    // 尝试从 IndexedDB 读取（由综合概览写入）
    const dbScores = await loadBranchScores()
    if (dbScores && Object.keys(dbScores).length > 0) {
      // 写入内存store供本页使用
      branchScoreStore.setScores(dbScores)
      console.log('[机构塑像] 已从IndexedDB读取评分数据，数量', Object.keys(dbScores).length)
    } else {
      console.warn('[机构塑像] 未检测到评分数据。请先打开“综合概览”页以加载评分后再回到本页。')
    }
  }
  
  // 加载前十大贷款户数据（如果store中没有）
  if (!branchScoreStore.hasTopLoansData.value) {
    isLoadingTopLoans.value = true
    try {
      const [topLoansData, topBadLoansData] = await Promise.all([
        fetchBranchTopLoans('20250930'),
        fetchBranchTopBadLoans('20250930')
      ])
      
      branchScoreStore.setTopLoans(topLoansData)
      branchScoreStore.setTopBadLoans(topBadLoansData)
      console.log('[机构画像] 前十大贷款户数据加载完成')
    } catch (err) {
      console.error('[机构画像] 前十大贷款户数据加载失败:', err)
    } finally {
      isLoadingTopLoans.value = false
    }
  } else {
    console.log('[机构画像] 从store读取前十大贷款户数据')
  }
})

// 获取风险等级样式类
const getRiskClass = (riskLevel) => {
  const level = String(riskLevel || '').trim()
  if (level === '5' || level === '次级' || level === '可疑' || level === '损失') {
    return 'risk-high'
  } else if (level === '3' || level === '关注') {
    return 'risk-medium'
  } else if (level === '1' || level === '正常') {
    return 'risk-low'
  }
  return 'risk-unknown'
}

// 获取风险等级标签
const getRiskLabel = (riskLevel) => {
  const level = String(riskLevel || '').trim()
  const riskMap = {
    '1': '正常',
    '2': '关注',
    '3': '次级',
    '4': '可疑',
    '5': '损失',
    '0': '未分类'
  }
  return riskMap[level] || level || '未知'
}

// 显示客户详情
const showCustomerDetail = (customer) => {
  selectedCustomer.value = customer
  showDetailDialog.value = true
}

// 获取排名样式类
const getRankClass = (index) => {
  if (index < 3) return 'rank-top3'
  if (index < 6) return 'rank-top6'
  return 'rank-normal'
}

// 监听store数据变化
watch(
  () => branchScoreStore.branchScores.value,
  (newScores) => {
    console.log('[机构塑像] store评分数据更新，共', Object.keys(newScores).length, '个支行')
  },
  { deep: true }
)
</script>

<style scoped>
.branch-profile-view {
  display: flex;
  width: 100%;
  height: calc(100vh - 90px);
  background: #033c76;
  gap: 15px;
  padding: 15px;
  overflow: hidden;
}

/* ========== 左侧支行列表面板 ========== */
.branch-list-panel {
  width: 350px;
  flex-shrink: 0;
  background: rgba(6, 30, 93, 0.5);
  border: 1px solid rgba(0, 215, 233, 0.3);
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.panel-header {
  padding: 20px;
  border-bottom: 1px solid rgba(0, 215, 233, 0.2);
  background: rgba(0, 215, 233, 0.05);
}

.header-title {
  color: #00d7e9;
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 8px;
}

.header-subtitle {
  color: #8b9dc3;
  font-size: 14px;
}

.branch-list-container {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

/* 自定义滚动条 */
.branch-list-container::-webkit-scrollbar {
  width: 6px;
}

.branch-list-container::-webkit-scrollbar-track {
  background: rgba(0, 0, 0, 0.1);
}

.branch-list-container::-webkit-scrollbar-thumb {
  background: rgba(0, 215, 233, 0.3);
  border-radius: 3px;
}

.branch-list-container::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 215, 233, 0.5);
}

/* 左侧加载状态 */
.list-loading {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
}

.loading-spinner-small {
  width: 40px;
  height: 40px;
  border: 3px solid rgba(0, 215, 233, 0.2);
  border-top-color: #00d7e9;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.loading-text-small {
  margin-top: 15px;
  color: #8b9dc3;
  font-size: 14px;
}

.branch-list-item {
  display: flex;
  align-items: center;
  padding: 15px;
  margin-bottom: 8px;
  background: rgba(0, 215, 233, 0.05);
  border: 1px solid rgba(0, 215, 233, 0.1);
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.branch-list-item:hover {
  background: rgba(0, 215, 233, 0.1);
  border-color: rgba(0, 215, 233, 0.3);
  transform: translateX(5px);
}

.branch-list-item.active {
  background: rgba(0, 215, 233, 0.2);
  border-color: #00d7e9;
  box-shadow: 0 0 10px rgba(0, 215, 233, 0.3);
}

.branch-rank {
  width: 40px;
  height: 40px;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 215, 233, 0.2);
  border-radius: 50%;
  color: #00d7e9;
  font-size: 18px;
  font-weight: bold;
  margin-right: 15px;
}

.branch-list-item.active .branch-rank {
  background: #00d7e9;
  color: #033c76;
}

.branch-info {
  flex: 1;
  min-width: 0;
}

.branch-name {
  color: #fff;
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.branch-org-no {
  color: #8b9dc3;
  font-size: 12px;
}

.branch-score {
  text-align: center;
  margin-left: 10px;
}

.score-value {
  font-size: 24px;
  font-weight: bold;
  line-height: 1;
  margin-bottom: 4px;
}

.score-label {
  color: #8b9dc3;
  font-size: 12px;
}

/* 评分颜色 */
.score-excellent {
  color: #52c41a;
}

.score-good {
  color: #00d7e9;
}

.score-normal {
  color: #fac858;
}

.score-poor {
  color: #ff4d4f;
}

/* ========== 右侧支行详情面板 ========== */
.branch-detail-panel {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  overflow-x: hidden;
}

/* 右侧详情面板滚动条样式 */
.branch-detail-panel::-webkit-scrollbar {
  width: 8px;
}

.branch-detail-panel::-webkit-scrollbar-track {
  background: rgba(0, 0, 0, 0.1);
  border-radius: 4px;
}

.branch-detail-panel::-webkit-scrollbar-thumb {
  background: rgba(0, 215, 233, 0.4);
  border-radius: 4px;
}

.branch-detail-panel::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 215, 233, 0.6);
}

/* 未选择状态 */
.no-selection {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 400px;
}

.no-selection-icon {
  font-size: 80px;
  margin-bottom: 20px;
  opacity: 0.5;
}

.no-selection-text {
  color: #8b9dc3;
  font-size: 18px;
}

/* 加载状态 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 400px;
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 4px solid rgba(0, 215, 233, 0.2);
  border-top-color: #00d7e9;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.loading-text {
  margin-top: 20px;
  color: #00d7e9;
  font-size: 16px;
}

/* 支行详情内容 */
.branch-content {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

/* 支行标题区 */
.branch-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 25px;
  background: rgba(6, 30, 93, 0.5);
  border: 1px solid rgba(0, 215, 233, 0.3);
  border-radius: 4px;
  margin-bottom: 10px;
}

.branch-title h2 {
  color: #fff;
  font-size: 28px;
  font-weight: 600;
  margin: 0 0 8px 0;
}

.branch-code {
  color: #8b9dc3;
  font-size: 14px;
}

.branch-score-display {
  flex-shrink: 0;
}

.score-circle {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 4px solid;
  background: rgba(0, 0, 0, 0.3);
  transition: all 0.3s ease;
}

.score-circle.score-excellent {
  border-color: #52c41a;
  box-shadow: 0 0 20px rgba(82, 196, 26, 0.5);
}

.score-circle.score-good {
  border-color: #00d7e9;
  box-shadow: 0 0 20px rgba(0, 215, 233, 0.5);
}

.score-circle.score-normal {
  border-color: #fac858;
  box-shadow: 0 0 20px rgba(250, 200, 88, 0.5);
}

.score-circle.score-poor {
  border-color: #ff4d4f;
  box-shadow: 0 0 20px rgba(255, 77, 79, 0.5);
}

.score-number {
  font-size: 36px;
  font-weight: bold;
  line-height: 1;
  margin-bottom: 5px;
}

.score-circle.score-excellent .score-number {
  color: #52c41a;
}

.score-circle.score-good .score-number {
  color: #00d7e9;
}

.score-circle.score-normal .score-number {
  color: #fac858;
}

.score-circle.score-poor .score-number {
  color: #ff4d4f;
}

.score-text {
  color: #8b9dc3;
  font-size: 14px;
}

/* 通用区块样式 */
.section {
  margin-bottom: 0;
}

.box {
  background: rgba(6, 30, 93, 0.5);
  border: 1px solid rgba(0, 215, 233, 0.3);
  border-radius: 4px;
  padding: 20px;
}

.tit {
  color: #00d7e9;
  font-size: 18px;
  font-weight: 500;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid rgba(0, 215, 233, 0.2);
}

/* 基础情况网格 */
.basic-info-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
}

.basic-info-card {
  display: flex;
  align-items: flex-start;
  gap: 15px;
  padding: 20px;
  background: rgba(0, 215, 233, 0.05);
  border: 1px solid rgba(0, 215, 233, 0.1);
  border-radius: 4px;
  transition: all 0.3s ease;
}

.basic-info-card:hover {
  background: rgba(0, 215, 233, 0.1);
  border-color: rgba(0, 215, 233, 0.3);
  transform: translateY(-3px);
  box-shadow: 0 5px 15px rgba(0, 215, 233, 0.2);
}

.info-icon {
  font-size: 40px;
  flex-shrink: 0;
  line-height: 1;
}

.info-content {
  flex: 1;
  min-width: 0;
}

.info-label {
  color: #8b9dc3;
  font-size: 14px;
  margin-bottom: 8px;
}

.info-value {
  display: flex;
  align-items: baseline;
  gap: 5px;
  margin-bottom: 8px;
}

.value-number {
  color: #fff;
  font-size: 28px;
  font-weight: bold;
  line-height: 1;
}

.value-unit {
  color: #8b9dc3;
  font-size: 14px;
}

.info-change {
  font-size: 13px;
}

.info-change.positive {
  color: #52c41a;
}

.info-change.negative {
  color: #ff4d4f;
}

.info-change.neutral {
  color: #faad14;
}

/* 占位区域 */
.placeholder-content {
  min-height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.1);
  border: 2px dashed rgba(0, 215, 233, 0.2);
  border-radius: 4px;
}

.placeholder-text {
  color: #8b9dc3;
  font-size: 16px;
  text-align: center;
  padding: 20px;
}

/* 异常指标分析样式 */
.section-abnormal-indicators {
  margin-top: 20px;
}

.tit-subtitle {
  margin-left: 10px;
  font-size: 12px;
  color: #8b9dc3;
  font-weight: normal;
}

.abnormal-content {
  min-height: 100px;
}

.no-abnormal {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  background: rgba(82, 196, 26, 0.05);
  border-radius: 8px;
  border: 1px solid rgba(82, 196, 26, 0.2);
}

.no-abnormal-icon {
  font-size: 48px;
  margin-bottom: 12px;
}

.no-abnormal-text {
  color: #52c41a;
  font-size: 16px;
}

.abnormal-grid {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.indicator-group {
  background: rgba(0, 0, 0, 0.2);
  border-radius: 8px;
  padding: 16px;
  border: 1px solid rgba(0, 215, 233, 0.2);
}

.group-header {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px 12px;
  border-radius: 6px;
  margin-bottom: 16px;
  font-weight: bold;
}

.excellent-header {
  background: linear-gradient(90deg, rgba(82, 196, 26, 0.15) 0%, rgba(82, 196, 26, 0.05) 100%);
  border-left: 4px solid #52c41a;
}

.risk-header {
  background: linear-gradient(90deg, rgba(255, 77, 79, 0.15) 0%, rgba(255, 77, 79, 0.05) 100%);
  border-left: 4px solid #ff4d4f;
}

.group-icon {
  font-size: 20px;
}

.group-title {
  color: #00d7e9;
  font-size: 16px;
}

.group-count {
  margin-left: auto;
  color: #8b9dc3;
  font-size: 14px;
  font-weight: normal;
}

.indicator-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 12px;
}

.indicator-card {
  background: rgba(0, 0, 0, 0.3);
  border-radius: 8px;
  padding: 14px;
  transition: all 0.3s ease;
  border: 1px solid transparent;
}

.indicator-card.excellent {
  border-color: rgba(82, 196, 26, 0.3);
}

.indicator-card.risk {
  border-color: rgba(255, 77, 79, 0.3);
}

.indicator-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 215, 233, 0.2);
}

.indicator-card.excellent:hover {
  border-color: #52c41a;
  box-shadow: 0 4px 12px rgba(82, 196, 26, 0.3);
}

.indicator-card.risk:hover {
  border-color: #ff4d4f;
  box-shadow: 0 4px 12px rgba(255, 77, 79, 0.3);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
  gap: 8px;
}

.indicator-name {
  color: #fff;
  font-size: 14px;
  font-weight: 500;
  flex: 1;
  line-height: 1.4;
}

.zscore-badge {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
  white-space: nowrap;
  flex-shrink: 0;
}

.zscore-badge.zscore-high {
  background: rgba(82, 196, 26, 0.2);
  color: #52c41a;
  border: 1px solid rgba(82, 196, 26, 0.5);
}

.zscore-badge.zscore-low {
  background: rgba(255, 77, 79, 0.2);
  color: #ff4d4f;
  border: 1px solid rgba(255, 77, 79, 0.5);
}

.card-body {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 10px;
}

.metric-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 0;
}

.metric-label {
  color: #8b9dc3;
  font-size: 12px;
}

.metric-value {
  color: #fff;
  font-size: 13px;
  font-weight: 500;
  font-family: 'Consolas', 'Monaco', monospace;
}

.metric-value.score-value {
  color: #faad14;
}

.card-footer {
  padding-top: 8px;
  border-top: 1px solid rgba(0, 215, 233, 0.1);
  display: flex;
  justify-content: flex-end;
}

.indicator-type {
  color: #8b9dc3;
  font-size: 11px;
  padding: 2px 6px;
  background: rgba(0, 215, 233, 0.1);
  border-radius: 3px;
}

/* 前十大贷款户样式 */
.section-top-loans,
.section-top-bad-loans {
  margin-top: 20px;
}

.top-loans-content,
.top-bad-loans-content {
  min-height: 200px;
  position: relative;
}

.loading-container-small,
.empty-container-small {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #8b9dc3;
}

.loading-spinner-small {
  width: 30px;
  height: 30px;
  border: 3px solid rgba(0, 215, 233, 0.2);
  border-top-color: #00d7e9;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

.loading-text-small {
  margin-top: 10px;
  font-size: 14px;
}

.empty-message {
  font-size: 14px;
}

/* 列表表格样式 */
.loans-list-table {
  overflow-x: auto;
  border-radius: 4px;
  border: 1px solid rgba(0, 215, 233, 0.2);
}

.loans-list-table table {
  width: 100%;
  border-collapse: collapse;
  background: rgba(0, 0, 0, 0.2);
}

.loans-list-table thead {
  background: rgba(0, 215, 233, 0.15);
}

.loans-list-table th {
  padding: 12px 16px;
  color: #00d7e9;
  font-weight: bold;
  text-align: left;
  border-bottom: 2px solid rgba(0, 215, 233, 0.3);
  font-size: 14px;
  white-space: nowrap;
}

.loans-list-table th.text-center {
  text-align: center;
}

.loans-list-table th.text-right {
  text-align: right;
}

.loans-list-table td {
  padding: 12px 16px;
  color: #fff;
  border-bottom: 1px solid rgba(0, 215, 233, 0.1);
  font-size: 13px;
}

.loans-list-table tbody tr {
  transition: all 0.2s;
  cursor: pointer;
}

.loans-list-table tbody tr:hover {
  background: rgba(0, 215, 233, 0.1);
  transform: translateX(2px);
}

.rank-cell {
  text-align: center;
}

.rank-badge {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 28px;
  height: 28px;
  border-radius: 50%;
  font-weight: bold;
  font-size: 13px;
}

.rank-badge.rank-top3 {
  background: linear-gradient(135deg, #ff6b6b 0%, #ff8787 100%);
  color: #fff;
  box-shadow: 0 2px 8px rgba(255, 107, 107, 0.4);
}

.rank-badge.rank-top6 {
  background: linear-gradient(135deg, #ffa940 0%, #ffc069 100%);
  color: #fff;
  box-shadow: 0 2px 8px rgba(255, 169, 64, 0.4);
}

.rank-badge.rank-normal {
  background: rgba(0, 215, 233, 0.2);
  color: #00d7e9;
  border: 1px solid rgba(0, 215, 233, 0.5);
}

.rank-badge.bad-rank.rank-top3 {
  background: linear-gradient(135deg, #ff4d4f 0%, #ff7875 100%);
}

.rank-badge.bad-rank.rank-top6 {
  background: linear-gradient(135deg, #ff7a45 0%, #ffa940 100%);
}

.customer-name {
  color: #00d7e9;
  font-weight: 500;
  font-size: 14px;
}

.amount-wan {
  text-align: right;
  color: #52c41a;
  font-weight: 500;
  font-family: 'Consolas', 'Monaco', monospace;
}

.bad-amount {
  color: #ff4d4f !important;
}

.loan-count {
  text-align: center;
  color: #8b9dc3;
}

.action-cell {
  text-align: center;
}

.detail-btn {
  padding: 4px 12px;
  background: rgba(0, 215, 233, 0.2);
  border: 1px solid rgba(0, 215, 233, 0.5);
  color: #00d7e9;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.2s;
}

.detail-btn:hover {
  background: rgba(0, 215, 233, 0.3);
  border-color: #00d7e9;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 215, 233, 0.3);
}

/* 客户详情弹窗样式 */
.detail-dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.85);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10000;
  padding: 20px;
  backdrop-filter: blur(5px);
}

.detail-dialog {
  background: linear-gradient(180deg, #0a2647 0%, #052041 100%);
  border: 2px solid #00d7e9;
  border-radius: 12px;
  max-width: 95vw;
  max-height: 90vh;
  width: 1400px;
  display: flex;
  flex-direction: column;
  box-shadow: 0 10px 40px rgba(0, 215, 233, 0.3);
  animation: slideUp 0.3s ease-out;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.dialog-header {
  padding: 20px 24px;
  border-bottom: 1px solid rgba(0, 215, 233, 0.3);
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: rgba(0, 215, 233, 0.05);
}

.dialog-header h3 {
  margin: 0;
  color: #00d7e9;
  font-size: 20px;
  font-weight: bold;
}

.close-btn {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: #fff;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  cursor: pointer;
  font-size: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.close-btn:hover {
  background: rgba(255, 77, 79, 0.2);
  border-color: #ff4d4f;
  color: #ff4d4f;
}

.dialog-body {
  padding: 24px;
  overflow-y: auto;
  flex: 1;
}

.customer-summary {
  display: flex;
  gap: 40px;
  padding: 16px 20px;
  background: rgba(0, 215, 233, 0.08);
  border-radius: 8px;
  margin-bottom: 20px;
  border-left: 4px solid #00d7e9;
}

.summary-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.summary-item .label {
  color: #8b9dc3;
  font-size: 14px;
}

.summary-item .value {
  color: #00d7e9;
  font-size: 18px;
  font-weight: bold;
}

.loans-table {
  overflow-x: auto;
  border-radius: 8px;
  border: 1px solid rgba(0, 215, 233, 0.2);
}

.loans-table table {
  width: 100%;
  min-width: 1200px;
  border-collapse: collapse;
  background: rgba(0, 0, 0, 0.2);
}

.loans-table thead {
  background: rgba(0, 215, 233, 0.15);
  position: sticky;
  top: 0;
  z-index: 10;
}

.loans-table th {
  padding: 12px 16px;
  color: #00d7e9;
  font-weight: bold;
  text-align: left;
  border-bottom: 2px solid rgba(0, 215, 233, 0.3);
  font-size: 13px;
  white-space: nowrap;
}

.loans-table td {
  padding: 12px 16px;
  color: #fff;
  border-bottom: 1px solid rgba(0, 215, 233, 0.1);
  font-size: 13px;
}

.loans-table tbody tr {
  transition: background 0.2s;
}

.loans-table tbody tr:hover {
  background: rgba(0, 215, 233, 0.08);
}

.text-right {
  text-align: right;
}

.text-highlight {
  color: #1890ff;
  font-weight: 500;
}

.text-amount {
  color: #52c41a;
  font-weight: 500;
}

.risk-badge {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.risk-badge.risk-high {
  background: rgba(255, 77, 79, 0.2);
  color: #ff4d4f;
  border: 1px solid rgba(255, 77, 79, 0.5);
}

.risk-badge.risk-medium {
  background: rgba(250, 173, 20, 0.2);
  color: #faad14;
  border: 1px solid rgba(250, 173, 20, 0.5);
}

.risk-badge.risk-low {
  background: rgba(82, 196, 26, 0.2);
  color: #52c41a;
  border: 1px solid rgba(82, 196, 26, 0.5);
}

.risk-badge.risk-unknown {
  background: rgba(139, 157, 195, 0.2);
  color: #8b9dc3;
  border: 1px solid rgba(139, 157, 195, 0.5);
}
</style>

